package main.java.juc;

/**
 * 线程之间的通信问题:生产着和消费者问题  等待唤醒，通知唤醒
 * 线程交替执行 A B 操作同一个变量 num = 0
 *
 */
public class ProducerConsumer01 {
    public static void main(String[] args) {
        Date date = new Date();
        new Thread(()->{
            for (int i = 0;i<10;i++){
                try {
                    date.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0;i<10;i++){
                try {
                    date.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0;i<10;i++){
                try {
                    date.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0;i<10;i++){
                try {
                    date.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}

class Date  {
    private int number = 0;
    // +1
    public synchronized void increment() throws InterruptedException {
        //这里用if会存在虚假唤醒的问题 所以用while
        while (number != 0){
            //等待
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"->"+number);
        this.notifyAll();
        //通知其他线程

    }

    // -1
    public synchronized void decrement() throws InterruptedException {
        while (number == 0){
            //等待
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"->"+number);
        //通知其他线程
        this.notifyAll();
    }
}
